//
//  SHSettingView.m
//  SimpleHappy
//
//  Created by 张超 on 15/11/25.
//  Copyright © 2015年 RockyFung. All rights reserved.
//  设置页面

#import "SHSettingView.h"
#import "Define.h"
#import "SHSettingCell.h"
#import "SDImageCache.h"

@interface SHSettingView ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *sHSetTableView;
@property (nonatomic, strong) SHSettingCell *cell;

@property (nonatomic, assign) double size; // 缓存大小

@property (nonatomic, strong) NSString *path; // 缓存位置


@end

@implementation SHSettingView

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [super myTitleLabel].text = @"设置";
    [[super registBtn] removeFromSuperview];
    
    self.sHSetTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, KScreenHeight / 10.42, KScreenWidth, KScreenHeight) style:UITableViewStyleGrouped];
    self.sHSetTableView.rowHeight = KScreenHeight / 11.12; // 行高
    
    [self.sHSetTableView registerClass:[SHSettingCell class] forCellReuseIdentifier:@"cell"]; // 注册
    
    self.sHSetTableView.delegate = self;
    self.sHSetTableView.dataSource = self;
    
    [self.view addSubview:self.sHSetTableView];
    
    // 计算缓存大小
    [self fileSize];
}


#pragma mark - 计算缓存大小
- (void)fileSize
{
    // 创建串行队列
    dispatch_queue_t queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{ // 串行、异步
        // Document位置
        self.path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
//      NSLog(@"%@", self.path);
//      NSLog(@"%@", [NSThread currentThread]);
        
        // 文件管理者
        NSFileManager *fm = [NSFileManager defaultManager];
        // 文件属性
        NSDictionary *attrs = [fm attributesOfItemAtPath:self.path error:nil];
        // 如果文件或文件夹不存在，或者路径错误，直接返回0
        if (attrs == nil) {
            self.size = 0;
        }
        if ([attrs.fileType isEqualToString:NSFileTypeDirectory]) { // 如果是文件夹
            // 获得文件夹的大小 == 文件夹中所有文件的总大小
            NSDirectoryEnumerator *enumerator = [fm enumeratorAtPath:self.path];
            for (NSString *subpath in enumerator) {
                NSString *fullSubpath = [self.path stringByAppendingPathComponent:subpath];
                // 累加文件大小
                self.size += [fm attributesOfItemAtPath:fullSubpath error:nil].fileSize;
            }
            // 缓存大小持久化
            NSUserDefaults *sizeDefaults = [NSUserDefaults standardUserDefaults];
            NSString *cacheSize = [NSString stringWithFormat:@"%.2f MB", self.size / 1000 / 1000];
            [sizeDefaults setObject:cacheSize forKey:@"cacheSize"];
        }
    });
}

#pragma mark - 清除缓存
- (void)clearDisk
{
    dispatch_queue_t queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        NSArray *file = [[NSFileManager defaultManager]subpathsAtPath:self.path];
        for (NSString *p in file) {
            NSError *error;
            NSString *cachPath = [self.path stringByAppendingPathComponent:p];
            if ([[NSFileManager defaultManager]fileExistsAtPath:cachPath]) {
                [[NSFileManager defaultManager]removeItemAtPath:cachPath error:&error];
            }
        }
        [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];
    });
}
#pragma mark - 缓存清理完成后执行
-(void)clearCacheSuccess
{
    // 刷新cell，重置缓存为0
    [self reloadCell];
    [self.cell.rightTextBtn setTitle:@"0.00 MB" forState:UIControlStateNormal];
    NSLog(@"清理成功");
    
}

- (void)viewDidAppear:(BOOL)animated
{
    // cell加载完成后刷新第一个cell，更新缓存大小
    [self reloadCell];
}

#pragma mark - 刷新第一个cell
- (void)reloadCell
{
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    [self.sHSetTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - 返回按钮的方法
- (void)backAction:(UIButton *)btn
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - 返回分区数、分区下行数、返回表头高度
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    if (section == 0) {
        return 2;
//    }
//    else
//    {
//        return 4;
//    }
}

#pragma mark - 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    self.cell.selectionStyle = UITableViewCellSelectionStyleNone;
    self.cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;// 小箭头
    NSArray *array1 = @[@"清除缓存",@"版本信息"];
//    NSArray *array2 = @[@"关于我们",@"服务及隐私条款",@"常见问题",@"给我们打分"];
    
    switch (indexPath.section) {
        case 0:{
            self.cell.leftTextLabel.text = array1[indexPath.row];
            if (indexPath.row == 0) {
                NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
                NSString *cacheSize = [userDefaultes stringForKey:@"cacheSize"];
                [self.cell.rightTextBtn setTitle:cacheSize forState:UIControlStateNormal];
                
                [self.cell.rightTextBtn addTarget:self action:@selector(clearDisk) forControlEvents:UIControlEventTouchUpInside];
            }
            else
            {
                self.cell.accessoryType = UITableViewCellAccessoryNone;
                
                NSString *str = [NSString stringWithFormat:@"%@ V",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
                [self.cell.rightTextBtn setTitle:str forState:UIControlStateNormal];
            }
        }
            break;
//        case 1:
//            self.cell.textLabel.text = array2[indexPath.row];
//            break;
    }
    return self.cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}



@end
